/*
 * FileFS.cpp
 *
 * Implementacia zdroja adresara: Filesystem
 *
 *  Created on: 1.4.2011
 *      Author: Tomas Srna
 */

#include "FileFS.h"

using namespace std;

FileFS::FileFS(std::string source) {
	this->source = source;
	fd = NULL;

	DIR* d = opendir(source.c_str());
	if(d == NULL) throw "Directory does not exist.";
	closedir(d);
}

void FileFS::open(const char * filename, const char * mode) {
	// Pokial mame nieco in otvorene, zavrime to!
	if(NULL != fd)
		this->close();

	std::string path(this->source);
	path.append("/");
	path.append(filename);
	if(NULL == (this->fd = fopen(path.c_str(), mode))) {
		string err("Cannot open file ");
		err.append(path);
		err.append(" for ");
		err.append(mode);
		err.append(".");
		throw err.c_str();
	}
}

int FileFS::read(void * buf, int len)  {
	if(NULL == fd) throw "No file is opened.";
	int r = fread(buf, len, 1, fd);
	if(ferror(fd))
		throw "Error reading file.";
	return r;
}

int FileFS::write(const void * buf, int len)  {
	if(NULL == fd) throw "No file is opened.";
	int r = fwrite(buf, len, 1, fd);
	if(ferror(fd))
		throw "Error writing file.";
	return r*len;
}

bool FileFS::eof() {
	if(NULL == fd) throw "No file is opened.";
	return feof(fd);
}

void FileFS::close() {
	if(NULL == fd) throw "No file is opened.";
	if(0 != fclose(fd))
		throw "Error closing file.";
	fd = NULL;
}

std::string FileFS::type() const {
	return std::string("Filesystem");
}

FileFS::~FileFS() {
	if(NULL == fd) return;
	fclose(fd);
}
